import React, { useState, useEffect } from 'react';
import { io } from 'socket.io-client';
import QRCode from 'react-qr-code';
import { useSelector, useDispatch } from 'react-redux'
import api from '../../api/api';
import { useNavigate } from 'react-router-dom'
import setUsrt from '../../store/parentCard'
const socket = io('ws://jerry.natapp1.cc');

function Index() {
    const dispatch = useDispatch()
    const [qrcodeUrl, setQrcodeUrl] = useState('');
    const navigate = useNavigate()
    useEffect(() => {
        socket.on('connect', () => {
            console.log('socket连接成功');

            socket.on('login_success', (userInfo) => {
                console.log('登录成功', userInfo);
                navigate('/layout/home')
            });

            socket.on('login_pending', () => {
                console.log('扫码');
            });
        });

    }, []);

    const getQRCodeURL = async () => {
        const res = await api.get('http://jerry.natapp1.cc/qrcode');
        const { qrcodeUrl, state } = res.data;

        setQrcodeUrl(qrcodeUrl);
        socket.emit('bind_state', state);
        // 存仓库
        dispatch(setUsrt(qrcodeUrl, state))
    };

    useEffect(() => {
        getQRCodeURL();
    }, []);

    return (
        <div>
            {
                qrcodeUrl ?
                    <QRCode value={qrcodeUrl} size={256} /> : ''
            }

        </div>
    );
}

export default Index;